// SPDX-FileCopyrightText: Adam Evyčędo
//
// SPDX-License-Identifier: GPL-3.0-or-later

package xyz.apiote.bimba.czwek.account

import android.content.Intent
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.fragment.app.Fragment
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import net.openid.appauth.AuthorizationException
import net.openid.appauth.AuthorizationResponse
import xyz.apiote.bimba.czwek.R
import xyz.apiote.bimba.czwek.account.fragments.AccountFragment
import xyz.apiote.bimba.czwek.account.fragments.LoginFragment
import xyz.apiote.bimba.czwek.data.sources.Server
import xyz.apiote.bimba.czwek.onboarding.FirstRunActivity
import xyz.apiote.bimba.czwek.repo.User
import xyz.apiote.bimba.czwek.settings.feeds.FeedChooserActivity


class AccountActivity : AppCompatActivity() {
	companion object {
		const val IN_FEEDS_TRANSACTION = "inFeedsTransaction"
	}

	var currentFragment: Fragment? = null

	private val authLauncher =
		registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
			when (currentFragment) {
				is LoginFragment -> {
					val resp = AuthorizationResponse.fromIntent(it.data!!)
					val ex = AuthorizationException.fromIntent(it.data)
					(currentFragment as LoginFragment).onAuthorization(resp, ex)
				}

				is AccountFragment -> {
					currentFragment = LoginFragment.newInstance()
					supportFragmentManager.beginTransaction()
						.replace(R.id.container, currentFragment!!)
						.commitNow()

				}
			}
		}


	override fun onCreate(savedInstanceState: Bundle?) {
		enableEdgeToEdge()
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_account)
		if (savedInstanceState == null) {
			currentFragment = if (User.load(this).isAuthenticated()) {
				AccountFragment.newInstance()
			} else {
				LoginFragment.newInstance()
			}
			supportFragmentManager.beginTransaction()
				.replace(R.id.container, currentFragment!!)
				.commitNow()
		}
	}

	fun moveOn(user: User, server: Server) {
		var move = true

		if (server.traffic!!.servers.all { it.seatsRequired.indexOf(user.seat.toString()) == -1 }) {
			MaterialAlertDialogBuilder(this).setIcon(
				AppCompatResources.getDrawable(
					this,
					R.drawable.error_gps
				)
			)
				.setTitle(getString(R.string.forbidden))
				.setMessage(getString(R.string.forbidden_server_message))
				.setPositiveButton(R.string.ok) { _, _ -> }
				.setNegativeButton(R.string.cancel) { _, _ -> move = false }
				.show()
		}

		if (move) {
			if (FirstRunActivity.getFirstRun(this)) {
				startActivity(Intent(this, FeedChooserActivity::class.java))
			} else {
				if (user.isAuthenticated()) {
					currentFragment = AccountFragment.newInstance()
					supportFragmentManager.beginTransaction()
						.replace(R.id.container, currentFragment!!)
						.commitNow()
				} else {
					finish()
				}
			}
		}
	}

	fun launchLogout(intent: Intent) {
		authLauncher.launch(intent)
	}

	fun launchLogin(authIntent: Intent) {
		authLauncher.launch(authIntent)
	}

	override fun onResume() {
		super.onResume()

		// TODO flashes on back from dashboard; should be e.g. start-activity-for-result
		if (!FirstRunActivity.getFirstRun(this)) {
			finish()
		}
	}
}